package javase.reflect;

import org.easymock.EasyMock;
import org.junit.Test;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;

/**
 * Java反射获取Request请求中的参数并封装到指定的JavaBean
 * User: Realfighter
 * Date: 2014/11/2
 * Time: 11:32
 */
public class RequestToJavaBean {

    @Test
    public void testRequestToJavaBean() {
        //创建Mock对象
        final HttpServletRequest request = EasyMock.createMock(HttpServletRequest.class);
        //设定Mock对象的预期行为和输出
//        EasyMock.expect(request.getParameter("name")).andReturn("Realfighter");
        EasyMock.expect(request.getParameterMap()).andReturn(new HashMap(){
            {
                put("name","Realfighter");
                put("sex","male");
            }
        });
        //将Mock对象切换到Replay状态
        EasyMock.replay(request);
        //到这里，我们已经“录制”了一个request对象
        JavaBean javaBean = (JavaBean) packReturnByRequest(request, new JavaBean());
        assertThat(javaBean.getName(), is("Realfighter"));
        assertThat(javaBean.getSex(), is("female"));//Expected :female Actual :male
    }

    class JavaBean {
        String name; //姓名
        String sex;  //性别

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public String getSex() {
            return sex;
        }

        public void setSex(String sex) {
            this.sex = sex;
        }
    }

    /**
     * 把request中的参数封装到指定的bean中
     *
     * @param request
     * @param obj
     * @return Object
     * @throws
     * @Title: packReturnByRequest
     * @author Realfighter
     */
    public static Object packReturnByRequest(HttpServletRequest request,
                                             Object obj) {
        Map<String, Object> keyMap = findKeyMapByRequest(request);
        Field field = null;
        Set<String> keys = keyMap.keySet();
        for (String key : keys) {
            try {
                field = obj.getClass().getDeclaredField(key);
                Class<?> beanType = field.getType();
                Object value = keyMap.get(key);
                String setMethodName = "set"
                        + key.substring(0, 1).toUpperCase() + key.substring(1);
                Method m;
                m = obj.getClass().getMethod(setMethodName, beanType);
                m.invoke(obj, value);
            } catch (Exception e1) {
                continue;
            }
        }
        return obj;
    }

    /**
     * 把request里面的参数转化成map
     *
     * @param request
     * @return Map<String,Object>
     * @throws
     * @Title: findKeyMapByRequest
     * @author Realfighter
     */
    private static Map<String, Object> findKeyMapByRequest(
            HttpServletRequest request) {
        //以下两种方式获取参数的map集合
        return request.getParameterMap();
//        Map<String, Object> keyMap = new HashMap<String, Object>();
//        Enumeration<?> enu = request.getParameterNames();
//        while (enu.hasMoreElements()) {
//            String paramname = (String) enu.nextElement();
//            String paramvalue = request.getParameter(paramname);
//            keyMap.put(paramname, paramvalue);
//        }
//        return keyMap;
    }

}
